package collection

import (
	"fmt"
	"unsafe"
)

func SliceTest() {
	var s1 []int
	//len是当前实际存放数据的长度，cap是切片当前的容量
	fmt.Println(s1, len(s1), cap(s1))
	s1 = append(s1, 1, 2, 3)
	fmt.Println(s1, len(s1), cap(s1))

	s2 := make([]int, 5, 10)
	fmt.Println(s2, len(s2), cap(s2))
	s2 = append(s2, 1, 2, 3, 4, 5, 6)
	//当切片长度超过容量后，容量会直接变为原来的*2
	fmt.Println(s2, len(s2), cap(s2))
	s2[0] = 88
	for k, v := range s2 {
		fmt.Println(k, v)
	}
}

// SliceSubTest 切片截取测试
func SliceSubTest() {
	var s3 = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	fmt.Println(s3, len(s3), cap(s3))
	fmt.Println("切片前四个元素：", s3[:4])
	fmt.Println("切片前后个元素：", s3[6:])
	//[2 3]
	fmt.Println("2-4个元素：", s3[2:4])
	//删除第一个元素
	s3 = s3[1:]
	//[1 2 3 4 5 6 7 8 9]
	fmt.Println("删除第一个元素:", s3)
	s3 = s3[:len(s3)-1]
	//[1 2 3 4 5 6 7 8]
	fmt.Println("删除最后一个元素:", s3)
	//删除下标为4的元素
	s3 = append(s3[0:4], s3[5:]...)
	//[1 2 3 4 6 7 8]
	fmt.Println("删除下标为4的元素:", s3)
}

func CopyTest() {
	var s1 = []int{1, 2, 3}
	s2 := s1
	fmt.Println(s1, s2)
	//s2修改下标为0的元素后，s1也会变更
	s2[0] = 100
	//[100 2 3] [100 2 3]
	fmt.Println(s1, s2)
}

func CopyNewTest() {
	var s1 = []int{1, 2, 3}
	s2 := make([]int, len(s1))
	s3 := s1
	copy(s2, s1)
	fmt.Println(s1, s2)
	//s2修改下标为0的元素后，s1也会变更
	s2[0] = 100
	//[100 2 3] [100 2 3]
	fmt.Println(s1, s2)
	fmt.Println(unsafe.Pointer(&s1))
	fmt.Println(unsafe.Pointer(&s2))
	fmt.Println(unsafe.Pointer(&s3))
	fmt.Println("s1第一个元素的内存地址:", unsafe.Pointer(&s1[0]))
	fmt.Println("s2第一个元素的内存地址:", unsafe.Pointer(&s2[0]))
	fmt.Println("s3第一个元素的内存地址:", unsafe.Pointer(&s3[0]))
}
